angular.module('starter')
.controller('onedayOrderCtrl', function($scope, $q, timeString,$interval, $ionicActionSheet, $timeout,$state,$stateParams, meilvFac, $location,$ionicModal,cfg) {
  $scope.baseMonth = new Date().getMonth();
  $scope.tmpsMonth = $scope.baseMonth;
  $scope.currentMonth = new Date().setMonth($scope.tmpsMonth,1);

  $scope.order = {};
  $scope.order.adultnum = 0;
  $scope.order.childernum = 0;
  $scope.order.childnum = 0;
  $scope.order.english_price = 1;
  $scope.order.need_english=1;
  $scope.order.article_id=$stateParams.id;
  $scope.events = [];
  $scope.ondayinfo = {};
  $scope.creatRandCode = function(){
    $scope.time = 60;
    var stop = $interval(function() {
      $scope.time --;
      if($scope.time<=0){
        $interval.cancel(stop);
        stop = undefined;
      }
    }, 1000);

    meilvFac.user.sendsms({phone:$scope.sendOrder.contact_num}, function(){  
    },function(data){
      alert(data.data.info);
    });      
  }

  $scope.getPrice = function(){
    meilvFac.articleshow.index(
      {article_id:$stateParams.id},
      function(data)
        {
          $scope.ondayinfo=data.info[0];
          $scope.order.title=$scope.ondayinfo.title;
          $scope.order.one_price=$scope.ondayinfo.one_price;
          $scope.order.two_price=$scope.ondayinfo.two_price;
          $scope.order.three_price=$scope.ondayinfo.three_price;
          $scope.order.four_price=$scope.ondayinfo.four_price;
          $scope.one_price=$scope.ondayinfo.one_price;
          $scope.two_price=$scope.ondayinfo.two_price;
          $scope.three_price=$scope.ondayinfo.three_price;
          $scope.four_price=$scope.ondayinfo.four_price;
          one_price=$scope.ondayinfo.one_price;
          two_price=$scope.ondayinfo.two_price;
          three_price=$scope.ondayinfo.three_price;
          four_price=$scope.ondayinfo.four_price;
        },
      function(data)
        {
          alert(data);
        }
    );
  };
  // $scope.getPrice();

  $scope.getHoliday = function(){
    var deferred = $q.defer();
    $scope.currentLastDay = new Date().setMonth($scope.tmpsMonth+1,1);
    $scope.currentLastDay = new Date($scope.currentLastDay).setHours(0,0,0,0)/1000-1;
    $scope.currentMonthInt = parseInt($scope.currentMonth/1000);
    meilvFac.holiday.holidayget({
      date_start: $scope.currentMonthInt,
      date_end: $scope.currentLastDay
    },function(data){
      $scope.holidays = data.info;
      angular.forEach($scope.holidays,function(holiday){
        var holidaytmp = {};
        var start = timeString.toDateString(holiday.date_start);
        var end = timeString.toDateString(holiday.date_end+24*3600);
        holidaytmp.start = start;
        holidaytmp.end = end;
        holidaytmp.rendering = 'background';
        holidaytmp.backgroundColor = '#FAE7C1';
        $scope.events.push(holidaytmp);
      });
      deferred.resolve();
    },function(data){
      alert(data.data.info);
    });
    return deferred.promise;
  };

  $scope.antichose = function(){
    var deferred = $q.defer();
    var holidayPromise = $scope.getHoliday();
    holidayPromise.then(function(){
      var priceEvents = [];//存放当前月price信息
      var year = new Date($scope.currentMonthInt*1000).getYear();
      var month = new Date($scope.currentMonthInt*1000).getMonth()+1;
      var today = new Date().getDay();
      var hour = new Date().getHours();
      var time = new Date().setHours(0,0,0,0)/1000;
      var i;

      if((today==5&&hour>=18)||today==6||today==0){
        if(today==0){
          today = 7;
        }
        for(i=1;i<=8-today;i++){
          var anti_e = {};
          anti_e.start = timeString.toDateString(time+i*24*3600);
          anti_e.end = timeString.toDateString(time+(i+1)*24*3600-1);
          anti_e.rendering = 'background';
          anti_e.backgroundColor = '#eee';
          priceEvents.push(anti_e);
        }
      }

      if(today<5&&today!=0&&hour>=18){
        var anti_e = {};
        anti_e.start = timeString.toDateString(time+24*3600);
        anti_e.end = timeString.toDateString(time+2*24*3600-1);
        anti_e.rendering = 'background';
        anti_e.backgroundColor = '#eee';
        priceEvents.push(anti_e);
      }
      
      $scope.events = $scope.events.concat(priceEvents);
      deferred.resolve();
    });
    
    return deferred.promise;
  };

  $scope.initCal = function(){
    // console.log($scope.events);
    var chosePromise = $scope.antichose();
    chosePromise.then(function(){
      $('#calendar').fullCalendar({
        // put your options and callbacks here
        lang: 'zh-cn',//显示语言
        header: false,
        defaultDate: $scope.currentMonth,
        columnFormat: 'dd',
        height: 363,
        selectable: true,
        editable: true,
        events: $scope.events,
        timezone: 'local',
        dragScroll: false,
        dayClick: function(date, jsEvent, view) {
          var today = new Date().getTime()/1000;
          var day = new Date().getDay();
          var hour = new Date().getHours();
          var time = new Date().setHours(0,0,0,0)/1000;
          var i = 0;
          //选中日期的时间戳
          $scope.order.datetime = timeString.toTimeNum(date.format());
          if((day==5&&hour>=18)||day==6||day==0){
            if(day==0){
              day = 7;
            }
            i = 8 - day;
          }
          if(day<5&&day!=0&&hour>=18){
            i = 1;
          }
          if($scope.order.datetime > today + i*3600*24){
            $(".fc-highlight").removeClass("fc-highlight");
            $(jsEvent.target).addClass("fc-highlight");
          }
          $scope.order.endtime=timeString.toTimeNum(date.format())+24*3600-1;
          meilvFac.holiday.holidayget({
            date_start: $scope.order.datetime,
            date_end: $scope.order.endtime
          },function(data){
            var day = new Date(date).getDay();
            if(data.info||day==6||day==0){
              $scope.ondayinfo.one_price=one_price*1.2;
              $scope.ondayinfo.two_price=two_price*1.2;
              $scope.ondayinfo.three_price=three_price*1.2;
              $scope.ondayinfo.four_price=four_price*1.2;
              $scope.order.one_price=$scope.ondayinfo.one_price;
              $scope.order.two_price=$scope.ondayinfo.two_price;
              $scope.order.three_price=$scope.ondayinfo.three_price;
              $scope.order.four_price=$scope.ondayinfo.four_price;
              $scope.one_price=one_price*1.2;
              $scope.two_price=two_price*1.2;
              $scope.three_price=three_price*1.2;
              $scope.four_price=four_price*1.2;
            }else{
              $scope.ondayinfo.one_price=one_price;
              $scope.ondayinfo.two_price=two_price;
              $scope.ondayinfo.three_price=three_price;
              $scope.ondayinfo.four_price=four_price;
              $scope.order.one_price=$scope.ondayinfo.one_price;
              $scope.order.two_price=$scope.ondayinfo.two_price;
              $scope.order.three_price=$scope.ondayinfo.three_price;
              $scope.order.four_price=$scope.ondayinfo.four_price;
              $scope.one_price=one_price;
              $scope.two_price=two_price;
              $scope.three_price=three_price;
              $scope.four_price=four_price;
            }
          },function(data){
            alert(data.data.info);
          })
        },
        select: function(startDate, endDate) {
          // console.log('select', startDate.format(), endDate.format());
        }
      });
      $('.fc-day-grid-container').css("overflow-y","hidden");
      $scope.current_day = $('#calendar').fullCalendar('getView').title;
    });
  };
  $scope.initCal();

  $scope.prev = function(){
    if($scope.tmpsMonth > $scope.baseMonth){
      $scope.tmpsMonth --;
      $scope.currentMonth = new Date().setMonth($scope.tmpsMonth,1);
      $scope.events = [];
      $scope.order.datetime = null;
      var chosePromise = $scope.antichose();
      chosePromise.then(function(){
        $('#calendar').fullCalendar('prev');
        $('#calendar').fullCalendar('removeEvents');
        $('#calendar').fullCalendar('addEventSource', $scope.events);
        $scope.current_day = $('#calendar').fullCalendar('getView').title;
      });
    }
  };

  $scope.next = function(){
    if($scope.tmpsMonth < $scope.baseMonth + 6){
      $scope.tmpsMonth ++;
      $scope.currentMonth = new Date().setMonth($scope.tmpsMonth,1);
      $scope.events = [];
      $scope.order.datetime = null;
      var chosePromise = $scope.antichose();
      chosePromise.then(function(){
        $('#calendar').fullCalendar('next');
        $('#calendar').fullCalendar('removeEvents');
        $('#calendar').fullCalendar('addEventSource', $scope.events);
        $scope.current_day = $('#calendar').fullCalendar('getView').title;
      });
    }
  };

  //监视日历左箭头，等于当前月份时，变为灰色
  $scope.$watch('tmpsMonth',function(){
    if($scope.tmpsMonth == $scope.baseMonth)
      $scope.downLimit = true;
    else
      $scope.downLimit = false;
  });

  //监视日历右箭头，等于当前月份+6时，变为灰色
  $scope.$watch('tmpsMonth',function(){
    if($scope.tmpsMonth == $scope.baseMonth + 6)
      $scope.upLimit = true;
    else
      $scope.upLimit = false;
  });

  // Triggered on a button click, or some other target
  $scope.minus = function(flag){
    switch(flag){
      case 1: if($scope.order.adultnum>0) $scope.order.adultnum--;break;
      case 2: if($scope.order.childernum>0) $scope.order.childernum--;break;
      case 3: if($scope.order.childnum>0) $scope.order.childnum--;break;
      default: return;
    }
  }; 

  $scope.plus = function(flag){
    switch(flag){
      case 1: $scope.order.adultnum++;break;
      case 2: $scope.order.childernum++;break;
      case 3: $scope.order.childnum++;break;
      default: return;
    }
  };

  $scope.totalprice=function(order,page){
    var adultnum = order.adultnum;
    var childernum = order.childernum;
    var childnum = order.childnum;
    one_price_=0;
    two_price_=0;
    three_price_=0;
    four_price_=0;
    if(page==1){
      switch(adultnum){
      case 1:
      return (adultnum+childernum*.7+childnum*.85)*$scope.one_price+(order.need_english==2?300:0);
      case 2:
      return (adultnum+childernum*.7+childnum*.85)*$scope.two_price+(order.need_english==2?300:0);
      case 3:
      return (adultnum+childernum*.7+childnum*.85)*$scope.three_price+(order.need_english==2?300:0);
      case 4:
      return (adultnum+childernum*.7+childnum*.85)*$scope.four_price+(order.need_english==2?300:0);
      default:
      return (adultnum+childernum*.7+childnum*.85)*$scope.four_price+(order.need_english==2?300:0);
      }
    }
    else if(page==2){
      switch(adultnum){
      case 1:
      return (adultnum+childernum*.7+childnum*.85)*$scope.sendOrder.one_price+(order.need_english==2?300:0);
      case 2:
      return (adultnum+childernum*.7+childnum*.85)*$scope.sendOrder.two_price+(order.need_english==2?300:0);
      case 3:
      return (adultnum+childernum*.7+childnum*.85)*$scope.sendOrder.three_price+(order.need_english==2?300:0);
      case 4:
      return (adultnum+childernum*.7+childnum*.85)*$scope.sendOrder.four_price+(order.need_english==2?300:0);
      default:
      return (adultnum+childernum*.7+childnum*.85)*$scope.sendOrder.four_price+(order.need_english==2?300:0);
      }
    }
  }

  $scope.orderNext=function(){
    if(!$scope.order.datetime){
      alert("请选择出发日期");
      return;
    }
    if(!$scope.order.adultnum&&!$scope.order.childernum&&!$scope.order.childnum){
      alert("至少选择一名游客");
      return;
    }
    if(!$scope.order.adultnum){
      alert("儿童至少有一位监护人陪同");
      return;
    }
    $state.go('tab.ordersteptwo',{orderdetail:$scope.order});
  }

  $scope.initOrder=function(){
    $scope.confirmC=true;
    $scope.sendOrder=$stateParams.orderdetail;
    $scope.sendOrder.adultArr=new Array($scope.sendOrder.adultnum);
    $scope.sendOrder.childArr=new Array($scope.sendOrder.childnum);
    $scope.sendOrder.childerArr=new Array($scope.sendOrder.childernum);
    for(var i=0;i<$scope.sendOrder.adultArr.length;i++){
        $scope.sendOrder.adultArr[i]={contact_type:1};
    }

    for(var k=0;k<$scope.sendOrder.childArr.length;k++){
        $scope.sendOrder.childArr[k]={contact_type:2,birth:null};
    }
    for(var j=0;j<$scope.sendOrder.childerArr.length;j++){
        $scope.sendOrder.childerArr[j]={contact_type:3,birth:null};
    }
    $scope.timeContainer=[];
    for(var i=12;i<44;i++){
      var time=$scope.sendOrder.datetime+i*1800;
      $scope.timeContainer.push(time);
    }
  }
  $scope.toggleConfirm=function(){
    $scope.confirmC=!$scope.confirmC;
  }
  $scope.goPay=function(){
    if(!$scope.confirmC){
      alert("请勾选阅读并同意一日游合同和退改规则");
      return;
    }
    $scope.sendOrder.contacts=[];
    var arrt=$scope.sendOrder.adultArr.concat($scope.sendOrder.childArr);
    var totalArr=arrt.concat($scope.sendOrder.childerArr);
    $scope.sendOrder.contacts=totalArr;
    meilvFac.oneday.orderAdd(
      $scope.sendOrder,
      function(data){
        window.location.href = cfg.baseUrl +'home/index/gotoPay/id/' + data.order_id;
      },
      function(data){
        alert(data.data.info);
      }
    )
  }
    var i=0;
    function resetAni(){
       var winH=$(window).height(),
        footerH=$('ion-footer-bar').height();
      $('.mask').height(winH-footerH);
      $('.mask').css({'top':-(winH-footerH)+'px'});
     
    }
   resetAni();

  $(".showOrder,.mask,.order-detail-wrap").click(function(event){
    i++;
    if(i%2){
      $(".order-detail-wrap").addClass('order-actived');
      $(".mask").show();
    }
    else{
      $(".order-detail-wrap").removeClass('order-actived');
      $(".mask").hide();
    }
  });

  $ionicModal.fromTemplateUrl('templates/buynotify.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.openModal = function() {
      $scope.modal.show();
    };
    $scope.closeModal = function() {
      $scope.modal.hide();
    };
    //当我们用到模型时，清除它！
    $scope.$on('$destroy', function() {
      $scope.modal.remove();
    });
    // 当隐藏的模型时执行动作
    $scope.$on('modal.hide', function() {
      // 执行动作
    });
    // 当移动模型时执行动作
    $scope.$on('modal.removed', function() {
      // 执行动作
    });
})